import java.util.Stack;

public class Offer_06 {
    /*输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
      示例 1：
      输入：head = [1,3,2]
      输出：[2,3,1]*/
    //遍历链表，将结果放到栈中，利用栈先进后出的特性来翻转链表
    public static int[] reversePrint(ListNode head) {
        ListNode listHead = head;
        Stack<Integer> stack = new Stack<>();
        while(listHead != null){
            stack.push(listHead.val);
            listHead = listHead.next;
        }
        int size = stack.size();
        int[] reverseArray = new int[size];
        for (int i = 0; i < size; i++) {
            reverseArray[i]=stack.pop();
        }
//不能够这么写因为stack.size()会随着stack的大小变化所以不可以这么写
/*        int[] reverseArray = new int[stack.size()];
        for (int i = 0; i < stack.size(); i++) {
            reverseArray[i]=stack.pop();
        }*/
        return reverseArray;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(3);
        ListNode node2 = new ListNode(2);
        head.next = node1;
        node1.next = node2;
        int[] array = reversePrint(head);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
}
